{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "a4baaa13",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'> <class 'int'>\n",
      "<class 'str'> <class 'int'>\n",
      "<class 'str'> <class 'int'>\n",
      "<class 'str'> <class 'int'>\n",
      "<class 'str'> <class 'int'>\n",
      "<class 'str'> <class 'int'>\n"
     ]
    }
   ],
   "source": [
    "import cv2 as cv\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# load template and searched image\n",
    "imgForSearch = cv.imread('../data/messi5.jpg',0)\n",
    "imgTemplate = cv.imread('../data/messi_face.jpg',0)\n",
    "# save for drawing matched rect \n",
    "w, h = imgTemplate.shape[::-1]\n",
    "\n",
    "# All the 6 methods for comparison in a list\n",
    "methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', \n",
    "           'cv.TM_CCORR',  'cv.TM_CCORR_NORMED', \n",
    "           'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']\n",
    "\n",
    "for meth in methods:\n",
    "    #we need keep org img to be searched every loop so \n",
    "    #we should draw sth on a new img in case that org img is changed\n",
    "    imgForDraw = imgForSearch.copy()\n",
    "    \n",
    "    # change string to int via python function eval\n",
    "    method = eval(meth)\n",
    "    print(type(meth), type(method))\n",
    "    \n",
    "    # Apply template Matching\n",
    "    res = cv.matchTemplate(imgForSearch,imgTemplate,method)\n",
    "    \n",
    "    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)\n",
    "    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum\n",
    "    if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:\n",
    "        top_left = min_loc\n",
    "    else:\n",
    "        top_left = max_loc\n",
    "    \n",
    "    # draw and visualize\n",
    "    bottom_right = (top_left[0] + w, top_left[1] + h)\n",
    "    cv.rectangle(imgForDraw, top_left,bottom_right, 255, 2)\n",
    "    cv.normalize( res, res, 0, 1, cv.NORM_MINMAX, -1 )\n",
    "#     print(res)\n",
    "#     break\n",
    "\n",
    "    cv.imshow(\"imgTemplate\", imgTemplate)\n",
    "    cv.imshow(\"imgOrg\", imgForSearch)\n",
    "    cv.imshow(\"matchRes\", res)\n",
    "    cv.imshow(\"imgForDraw\", imgForDraw)\n",
    "    cv.waitKey(0)\n",
    "\n",
    "cv.destroyAllWindows()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "3f3102e1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(468, 448, 3)\n",
      "(468, 448)\n",
      "(32, 24)\n",
      "<class 'tuple'>\n",
      "<class 'zip'> <zip object at 0x00000247E6E1B5C0>\n"
     ]
    }
   ],
   "source": [
    "import cv2 as cv\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "img_rgb = cv.imread('../data/mario.png')\n",
    "print(img_rgb.shape)\n",
    "img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)\n",
    "print(img_gray.shape)\n",
    "template = cv.imread('../data/mario_coin.png',0)\n",
    "print(template.shape)\n",
    "w, h = template.shape[::-1]\n",
    "\n",
    "res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)\n",
    "\n",
    "threshold = 0.9\n",
    "loc = np.where( res >= threshold)\n",
    "print(type(loc))\n",
    "# print(type(*loc[::-1]))\n",
    "print(type(zip(*loc[::-1])), zip(*loc[::-1]))\n",
    "for pt in zip(*loc[::-1]):\n",
    "    cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)\n",
    "#     cv.imshow(\"img_rgb\", img_rgb)\n",
    "#     cv.waitKey(0)\n",
    "\n",
    "cv.imshow(\"res\", res)\n",
    "cv.imshow(\"img_rgb\", img_rgb)\n",
    "cv.waitKey(0)\n",
    "cv.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "c9db360f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(468, 448, 3)\n",
      "(468, 448)\n",
      "(32, 24)\n"
     ]
    }
   ],
   "source": [
    "# my method for extracting the drawing rect location\n",
    "import cv2 as cv\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "img_rgb = cv.imread('../data/mario.png')\n",
    "img_org = img_rgb.copy()\n",
    "print(img_rgb.shape)\n",
    "img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)\n",
    "print(img_gray.shape)\n",
    "template = cv.imread('../data/mario_coin.png',0)\n",
    "print(template.shape)\n",
    "w, h = template.shape[::-1]\n",
    "\n",
    "res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)\n",
    "\n",
    "threshold = 0.9\n",
    "loc = np.where( res >= threshold)\n",
    "\n",
    "cordXs,cordYs = loc[1],loc[0]\n",
    "for idx,X in enumerate(cordXs):\n",
    "    cv.rectangle(img_rgb, (X,cordYs[idx]), (X + w, cordYs[idx] + h), \n",
    "                 (0,0,255), 1)\n",
    "\n",
    "cv.imshow(\"res\", res)\n",
    "cv.imshow(\"img_org\", img_org)\n",
    "cv.imshow(\"img_rgb\", img_rgb)\n",
    "cv.waitKey(0)\n",
    "cv.destroyAllWindows()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b29cbf6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "#get max similarity in regoin \n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
